/**
 * 发送http请求
 * 依赖 md5.js 用于建立缓存
 * 依赖 zbNotice.js 用于提醒
 */
let zbCache = {}
const zbRequest = function () {
    this.cacheTime = 300;
    this.successCode = 1;
    this.success = null;
    this.error = null;
    this.sync = false; //true:异步 false:同步
    this.method = 'post'; //post/get
    this.defaultParams = {};

    //默认成功回调
    this.defaultSuccess = function () {
        nt.text('操作成功！');
    }

    //默认错误回调
    this.defaultError = function (msg=null) {
        if (msg) {
            nt.text(msg);
        } else {
            nt.text('操作失败！');
        }
    }

    //获取时间戳
    this.getTimestamp = function(){
        let now = (new Date()).getTime();
        now = now.toString().slice(0, -3);
        return parseInt(now);
    }

    //获取信息摘要
    this.getHash = function (src, arg) {
        return hex_md5(src + JSON.stringify(arg)); //依赖md5.js
    }

    //获取缓存
    this.getCache = function(src, arg) {
        let key = this.getHash(src, arg);

        if (zbCache[key] === undefined) {
            console.log('未找到缓存: ' + src + ' ' +key);
            return null;
        } else {
            let expire = parseInt(zbCache[key]['expire']);
            let now = this.getTimestamp();
            if (now >= expire) {
                console.log('缓存已过期 ' + src);
                return null;
            } else {
                console.log('找到缓存 ' + src);
                return zbCache[key]['data'];
            }
        }
    }

    this.setCache = function(src, arg, data, expire) {
        let key = this.getHash(src, arg);
        let now = this.getTimestamp();

        expire = now + expire;
        zbCache[key] = {expire:expire, data:data}
    }

    //请求接口
    this.request = function (src, params = {}, success = null) {
        for (let k in this.defaultParams) {
            params[k] = this.defaultParams[k];
        }
        let ch = this.getCache(src, params)
        if (ch !== null && typeof this.success === 'function') {
            success(ch);
            return;
        }

        let that = this;

        let form = new FormData(); // FormData 对象
        let xhr = new XMLHttpRequest();  // XMLHttpRequest 对象
        xhr.open("post", src, this.async); //post方式，url为服务器请求地址，true 该参数规定请求是否异步处理。
        xhr.onload = function (evt) {
            let rs = JSON.parse(xhr.response);
            if (rs) {
                that.setCache(src, params, rs['data'], that.cacheTime);
                if (rs['code'] === that.successCode) {
                    if (typeof success === 'function') {
                        success(rs['data']);
                    } else {
                        that.defaultSuccess();
                    }

                } else {
                    if (typeof that.error === 'function') {
                        that.error(rs['message']);
                    } else {
                        that.defaultError(rs['message']);
                    }
                }
            } else {
                console.log('返回数据不是json');
                return false;
            }
        }

        //请求失败
        xhr.onerror =  function(evt) {
            console.log(xhr.response);
            that.defaultError();
        };

        //请求超时
        xhr.ontimeout =  function(evt) {
            that.defaultError('请求超时.');
        };

        for (let i in params) {
            form.append(i, params[i]);
        }
        xhr.send(form); //开始上传，发送form数据
    }
}
